package com.zhh.nio;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Response {
    
    private String statusCode = "200";
    private String CLRF ="\r\n";
  
    private final static Map<String,String> statusLine;
    private NioSession session;
    private Map<String,String> headers;
    static{
        statusLine = new HashMap<String,String>();
        statusLine.put("200", "HTTP/1.1 200 OK");
        statusLine.put("404", "HTTP/1.1 404 Not Find");
    }
    public Response(NioSession session){
        this.session = session;
        headers = new LinkedHashMap<String,String>();
        headers.put("Content-Type","text/html; charset=UTF-8");
        //headers.put("Transfer-Encoding", "chunked");
        headers.put("Connection", "close");
    }
    
    public void addHeader(String name,String value){
        
        headers.put(name, value);
    }
    
    public void writeHeader(){
        
        session.write(headToStr());
    }
    
    public void writeStatusCode(){
        
        session.write(statusLine.get(statusCode) + CLRF);
    }
    
    /**fake interface just for test
     * @param body
     */
    public void writeBody(String body){
        
        session.write(body);
    }
    
    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

    public String headToStr(){
        Iterator<Entry<String, String>> iter = headers.entrySet().iterator();
        StringBuilder headStr = new StringBuilder(32);
        headStr.append(statusLine.get(statusCode)).append(CLRF);
        while(iter.hasNext()){
            Entry<String,String> item = iter.next();
             headStr.append(item.getKey()).append(": ").append(item.getValue());
             headStr.append(CLRF);
        }
        headStr.append(CLRF);
        
        return headStr.toString();
    }
    
    
    
    
}
